﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Directory.BLL;
using Directory.Web;
using Directory.Model;
using Newtonsoft.Json;

public partial class A_ajax : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string action = Request.QueryString["action"];
        string cIdStr = Request.QueryString["cid"];
        string pIdStr = Request.QueryString["pid"];
        int cId;
        int pId;
        switch (action)
        {
            case "getcategories":
                if (!int.TryParse(pIdStr, out pId))
                {
                    pId = 0;
                }
                ResponseGetCategories(pId);
                break;
            case "getitems":
                if (!int.TryParse(cIdStr, out cId))
                {
                    cId = 0;
                }
                ResponseGetItems(cId);
                break;
            case "getuncheckeditems":
                ResponseGetUncheckedItems();
                break;
            case "getrecursiveparents":
                if (!int.TryParse(cIdStr, out cId))
                {
                    cId = 0;
                }
                ResponseGetRecursiveParents(cId);
                break;
            case "saveitem":
                ResponseSaveItem(Request);
                break;
            case "deleteitems":
                ResponseDeleteItem(Request);
                break;
            case "additem":
                ResponseAddItem(Request);
                break;
            case "addbatitem":
                if (!int.TryParse(cIdStr, out cId))
                {
                    WriteJsonError("目录为空。");
                    return;
                }
                ResponseAddBatchItem(cId, Request);
                break;
            case "checkitems":
                ResponseCheckItem(Request);
                break;
            case "deletecategoryies":
                ResponseDeleteCategory(Request);
                break;
            case "addcategory":
                ResponseAddCategory(Request);
                break;
            case "bataddcategory":
                ResponseBatAddCategory(Request);
                break;
            case "savecategory":
                ResponseSaveCategory(Request);
                break;
            case "getcategoryinfo":
                if (!int.TryParse(cIdStr, out cId))
                {
                    cId = 0;
                }
                ResponseGetCategoryInfo(cId);
                break;
            case "addrootcategory":
                ResponseAddRootCategory(Request);
                break;
            case "getrecommandcategory":
                ResponseGetRecommandCategory();
                break;
            case "unrecommandcategoryies":
                ResponseUnRecommandCategory(Request);
                break;
            case "recommandcategory":
                if (!int.TryParse(cIdStr, out cId))
                {
                    cId = 0;
                }
                ResponseRecommandCategoryInfo(cId);
                break;
        }
        Response.End();
    }

    private void ResponseRecommandCategoryInfo(int cId)
    {
        if (cId < 1)
        {
            WriteJsonError("CategoryId为空。");
            return;
        }
        CategoryDataProxy.RecommandCategory(cId);
        WriteJsonResult(null);
    }

    private void ResponseUnRecommandCategory(HttpRequest request)
    {
        string idsStr = request.QueryString["categoryids"];
        if (string.IsNullOrEmpty(idsStr))
        {
            WriteJsonError("CategoryId 为空。");
            return;
        }
        string[] idsArr = idsStr.Split(new char[] { ',' });
        List<int> succeedList = new List<int>();
        int cId;
        foreach (string idStr in idsArr)
        {
            if (int.TryParse(idStr, out cId))
            {
                CategoryDataProxy.UnrecommandCategory(cId);
                succeedList.Add(cId);
            }
        }
        WriteJsonResult(succeedList);
    }

    private void ResponseGetRecommandCategory()
    {
        int totalcount;
        IList<CategoryInfo> list = CategoryDataProxy.GetRecommandCategories(0, 999, out totalcount);
        WriteJsonResult(list);
    }

    private void ResponseAddRootCategory(HttpRequest request)
    {
        string name = request.Form["CategoryName"];
        string orderStr = request.Form["Order"];
        if (name == null || (name = name.Trim()) == string.Empty)
        {
            WriteJsonError("目录名为空。");
            return;
        }
        int order;
        if (!int.TryParse(orderStr, out order))
        {
            order = -1;
        }
        CategoryInfo.ErrorCode err;
        CategoryDataProxy.CreateCategory(name, WebSettings.GetInstance().RootCategoryId, string.Empty, string.Empty, order, out err);
        if (err == CategoryInfo.ErrorCode.Success)
        {
            WriteJsonResult(null);
        }
        else
        {
            WriteJsonError("保存失败，" + err.ToString() + "。");
        }
    }

    private void ResponseGetCategoryInfo(int cId)
    {
        if (cId <= 0)
        {
            WriteJsonError("CategoryId不合法");
            return;
        }
        CategoryInfo cat = CategoryDataProxy.GetCategory(cId);
        if (cat == null)
        {
            WriteJsonError("该目录不存在，可能已经被删除。");
            return;
        }
        WriteJsonResult(cat);
    }

    private void ResponseSaveCategory(HttpRequest request)
    {
        string cIdStr = request.Form["CategoryId"];
        string name = request.Form["CategoryName"];
        string pIdStr = request.Form["ParentCategoryId"];
        string orderStr = request.Form["Order"];
        int cId;
        if (!int.TryParse(cIdStr, out cId))
        {
            WriteJsonError("CategoryId为空。");
            return;
        }
        if (name == null || (name = name.Trim()) == string.Empty)
        {
            WriteJsonError("目录名为空。");
            return;
        }
        int pId;
        if (!int.TryParse(pIdStr, out pId))
        {
            WriteJsonError("所属目录为空。");
            return;
        }
        int order;
        if (!int.TryParse(orderStr, out order))
        {
            order = -1;
        }
        CategoryInfo cat = CategoryDataProxy.GetCategory(cId);
        if (cat == null)
        {
            WriteJsonError("该目录不存在，可能已经被其它用户删除。");
            return;
        }

        cat.CategoryName = name;
        cat.ParentCategoryId = pId;
        cat.Order = order;

        CategoryInfo.ErrorCode error;
        CategoryDataProxy.UpdateCategoryInfo(cat, out error);
        if (error == CategoryInfo.ErrorCode.Success)
        {
            WriteJsonResult(cat);
        }
        else
        {
            WriteJsonError("保存失败，" + error.ToString() + "。");
        }
    }

    private void ResponseBatAddCategory(HttpRequest request)
    {
        string pidStr = request.Form["pid"];
        int pid;
        if (!int.TryParse(pidStr, out pid))
        {
            WriteJsonError("没有所属目录。");
            return;
        }
        string nameStr = request.Form["name"];
        if (string.IsNullOrEmpty(nameStr))
        {
            WriteJsonError("目录名为空。");
            return;
        }
        string[] name = nameStr.Split(new char[] { '\n' });

        Directory.Model.CategoryInfo.ErrorCode errorCode;
        int succeed = 0, count = name.Length;

        for (int i = 0; i < count; i++)
        {
            string t = name[i];
            if (string.IsNullOrEmpty(t))
                continue;
            CategoryDataProxy.CreateCategory(t, pid, string.Empty, string.Empty, -1, out errorCode);
            if (errorCode == CategoryInfo.ErrorCode.Success)
            {
                succeed++;
            }
        }
        if (succeed == count)
        {
            WriteJsonResult("成功添加" + succeed + "项。");
        }
        else
        {
            WriteJsonError("共提交 " + count + " 项，成功添加" + succeed + "项。");
        }
        return;
    }

    private void ResponseAddCategory(HttpRequest request)
    {
        string name = request.Form["CategoryName"];
        string pIdStr = request.Form["ParentCategoryId"];
        string orderStr = request.Form["Order"];
        if (name == null || (name = name.Trim()) == string.Empty)
        {
            WriteJsonError("目录名为空。");
            return;
        }
        int pId;
        if (!int.TryParse(pIdStr, out pId))
        {
            WriteJsonError("所属目录为空。");
            return;
        }
        int order;
        if (!int.TryParse(orderStr, out order))
        {
            order = -1;
        }
        CategoryInfo.ErrorCode error;
        CategoryDataProxy.CreateCategory(name, pId, string.Empty, string.Empty, order, out error);
        if (error == CategoryInfo.ErrorCode.Success)
        {
            WriteJsonResult(null);
        }
        else
        {
            WriteJsonError("保存失败，" + error.ToString() + "。");
        }
    }

    private void ResponseDeleteCategory(HttpRequest request)
    {
        string idsStr = request.QueryString["categoryids"];
        if (string.IsNullOrEmpty(idsStr))
        {
            WriteJsonError("CategoryId 为空。");
            return;
        }
        string[] idsArr = idsStr.Split(new char[] { ',' });
        List<int> succeedList = new List<int>();
        int cId;
        foreach (string idStr in idsArr)
        {
            if (int.TryParse(idStr, out cId))
            {
                CategoryDataProxy.DeleteCategory(cId);
                succeedList.Add(cId);
            }
        }
        WriteJsonResult(succeedList);
    }

    private void ResponseCheckItem(HttpRequest request)
    {
        string idsStr = request.QueryString["itemids"];
        if (string.IsNullOrEmpty(idsStr))
        {
            WriteJsonError("ItemId 为空。");
            return;
        }
        string[] idsArr = idsStr.Split(new char[] { ',' });
        List<int> succeedList = new List<int>();
        int itemId;
        foreach (string idStr in idsArr)
        {
            if (int.TryParse(idStr, out itemId))
            {
                ItemDataProxy.UpdateCheckState(itemId, true);
                succeedList.Add(itemId);
            }
        }
        WriteJsonResult(succeedList);
    }

    private void ResponseAddBatchItem(int cId, HttpRequest request)
    {
        if (cId == WebSettings.GetInstance().RootCategoryId)
        {
            WriteJsonError("不能添加到根目录。");
            return;
        }
        string titleStr = request.Form["title"];
        if (string.IsNullOrEmpty(titleStr))
        {
            WriteJsonError("未输入标题。");
            return;
        }
        string urlStr = request.Form["url"];
        string[] title = titleStr.Split(new char[] { '\n' });
        string[] linkurl = urlStr.Split(new char[] { '\n' });
        int count = title.Length;
        string author = HttpContext.Current.User.Identity.Name;
        Directory.Model.ItemInfo.ErrorCode errorCode;
        int succeed = 0;
        for (int i = 0; i < count; i++)
        {
            string t = title[i];
            if (string.IsNullOrEmpty(t))
                continue;
            string u = linkurl.Length > i ? linkurl[i] : string.Empty;
            ItemDataProxy.CreateItem(cId, t, string.Empty, string.Empty, u, string.Empty, author, author, 0, false, true, out errorCode);
            if (errorCode == ItemInfo.ErrorCode.Success)
            {
                succeed++;
            }
        }
        if (succeed == count)
        {
            WriteJsonResult("成功添加" + succeed + "项。");
        }
        else
        {
            WriteJsonError("共提交 " + count + " 项，成功添加" + succeed + "项。");
        }
        return;
    }

    private void ResponseAddItem(HttpRequest request)
    {
        string title = request.Form["Title"];
        string cIdStr = request.Form["CategoryId"];
        string des = request.Form["Description"];
        string url = request.Form["LinkUrl"];
        string logo = request.Form["LogoPath"];
        string topStr = request.Form["TopState"];

        if (title == null || (title = title.Trim()) == string.Empty)
        {
            WriteJsonError("标题为空。");
            return;
        }
        int cId;
        if (!int.TryParse(cIdStr, out cId))
        {
            WriteJsonError("目录为空。");
            return;
        }
        else if (cId == WebSettings.GetInstance().RootCategoryId)
        {
            WriteJsonError("不能添加到根目录。");
            return;
        }
        int top;
        if (!int.TryParse(topStr, out top))
        {
            top = 0;
        }

        string author = HttpContext.Current.User.Identity.Name;

        ItemInfo.ErrorCode err;
        ItemDataProxy.CreateItem(cId, title, string.Empty, des, url, logo, author, author, top, false, true, out err);
        if (err == ItemInfo.ErrorCode.Success)
        {
            WriteJsonResult(null);
        }
        else
        {
            WriteJsonError("保存失败，" + err.ToString() + "。");
        }
    }

    private void ResponseDeleteItem(HttpRequest request)
    {
        string idsStr = request.QueryString["itemids"];
        if (string.IsNullOrEmpty(idsStr))
        {
            WriteJsonError("ItemId 为空。");
            return;
        }
        string[] idsArr = idsStr.Split(new char[] { ',' });
        List<int> succeedList = new List<int>();
        int itemId;
        foreach (string idStr in idsArr)
        {
            if (int.TryParse(idStr, out itemId))
            {
                ItemDataProxy.DeleteItem(itemId);
                succeedList.Add(itemId);
            }
        }
        WriteJsonResult(succeedList);
    }

    private void ResponseSaveItem(HttpRequest request)
    {
        string idStr = request.Form["ItemId"];
        string title = request.Form["Title"];
        string cIdStr = request.Form["CategoryId"];
        string des = request.Form["Description"];
        string url = request.Form["LinkUrl"];
        string logo = request.Form["LogoPath"];
        string topStr = request.Form["TopState"];
        string isCheckedStr = request.Form["IsChecked"];

        int itemId;
        if (!int.TryParse(idStr, out itemId))
        {
            WriteJsonError("参数ItemId为空。");
            return;
        }
        if (title == null || (title = title.Trim()) == string.Empty)
        {
            WriteJsonError("标题不能为空。");
            return;
        }
        int cId;
        if (!int.TryParse(cIdStr, out cId))
        {
            WriteJsonError("目录不能为空。");
            return;
        }
        else if (cId == WebSettings.GetInstance().RootCategoryId)
        {
            WriteJsonError("不能移动到根目录。");
            return;
        }

        ItemInfo item = ItemDataProxy.GetItemInfo(itemId);
        if (item != null)
        {
            item.Title = title;
            item.Description = des;
            item.LinkUrl = url;
            item.LogoPath = logo;
            item.CategoryId = cId;

            int topState;
            if (int.TryParse(topStr, out topState))
            {
                item.TopState = topState;
            }
            bool isChecked;
            if (bool.TryParse(isCheckedStr, out isChecked))
            {
                isChecked = true;
            }
            item.IsChecked = isChecked;

            ItemInfo.ErrorCode err;
            ItemDataProxy.UpdateItemInfo(item, out err);
            if (err == ItemInfo.ErrorCode.Success)
            {
                WriteJsonResult(item);
            }
            else
            {
                WriteJsonError("保存失败，" + err.ToString() + "。");
            }
        }
        else
        {
            WriteJsonError("该条文不存在，可能已经被其它用户删除。");
            return;
        }
    }

    private void ResponseGetRecursiveParents(int cId)
    {
        IList<CategoryInfo> list = CategoryDataProxy.GetRecursiveParentsOfCategory(cId);
        WriteJsonResult(list);
    }

    private void ResponseGetUncheckedItems()
    {
        int total;
        IList<ItemInfo> list = ItemDataProxy.GetUncheckedItems4User(HttpContext.Current.User.Identity.Name, 0, 9999, out total);
        WriteJsonResult(list);
    }

    private void ResponseGetItems(int cId)
    {
        int total;
        IList<ItemInfo> list = ItemDataProxy.GetItemsInCategory(cId, 0, 9999, out total);
        WriteJsonResult(list);
    }

    private void ResponseGetCategories(int pId)
    {
        if (pId == 0)
        {
            IList<CategoryInfo> list = CategoryDataProxy.GetRootCategoriesForUser(HttpContext.Current.User.Identity.Name);
            WriteJsonResult(list);
        }
        else
        {
            IList<CategoryInfo> list = CategoryDataProxy.GetChildsOfCategory(pId);
            WriteJsonResult(list);
        }
    }

    private void WriteJsonResult(object obj)
    {
        Response.Clear();
        Response.ContentType = "application/json";

        JsonResponse r = new JsonResponse(obj, null);
        string str = JsonConvert.SerializeObject(r);

        Response.Write(str);
        Response.Flush();
        Response.End();
    }

    private void WriteJsonError(object err)
    {
        Response.Clear();
        Response.ContentType = "application/json";

        JsonResponse r = new JsonResponse(null, err);
        string str = JsonConvert.SerializeObject(r);

        Response.Write(str);
        Response.Flush();
        Response.End();
    }

    class JsonResponse
    {
        public JsonResponse() : this(null, null) { }

        public JsonResponse(object result, object error)
        {
            this.Result = result;
            this.Error = error;
        }

        private object _error;
        public object Error
        {
            get { return _error; }
            set { _error = value; }
        }

        private object _result;
        public object Result
        {
            get { return _result; }
            set { _result = value; }
        }
    }
}
